<?php


namespace App\Socket\WebSocket;

//消息解析器
use App\Socket\WebSocket\MessageServer\BaseMessage;
use EasySwoole\EasySwoole\ServerManager;
use EasySwoole\Socket\AbstractInterface\ParserInterface;
use EasySwoole\Socket\Bean\Caller;
use EasySwoole\Socket\Bean\Response;
use EasySwoole\Socket\Client\WebSocket;

class WebSocketParser implements ParserInterface
{

    /**
     * @param $raw string 客户端原始消息
     * @param WebSocket $client WebSocket Client 对象
     * @return Caller|null  Socket  调用对象
     * @throws \Exception
     *
     */
    public function decode($raw, $client): ?Caller
    {
        // 解析 客户端接受原始消息
        $data = json_decode($raw, true);
        if (!is_array($data)) {
            throw new \Exception('消息格式错误');
            return null;
        }
        // new 调用者原始对象
        $caller = new Caller();
        // 设置传达处理消息业务逻辑的类  默认消息处理类WebSocketMessage
        $class = '\\App\\Socket\\WebSocket\\MessageServer\\' . ucfirst($data['class'] ?? 'WebSocketMessage');
        $caller->setControllerClass($class);
        // 设置被调用的方法  默认方法 run
        $caller->setAction($data['action'] ?? 'run');
        // 检查是否存在 content 消息内容处理
        if (!empty($data['content'])) {
            // content 无法解析为array 时 返回 content => string 格式
            $args = is_array($data['content']) ? $data['content'] : ['content' => $data['content']];
        }
        // 设置被调用的Args
        $caller->setArgs($args ?? []);
        return $caller;
    }

    /**
     * @param Response $response
     * @param $client
     * @return string|null   发送给客户端的消息
     */
    public function encode(Response $response, $client): ?string
    {
        return $response->getMessage();
    }

}
